03. CORS
CORS
If you've had a little experience as a web developer, you may have seen an error in the browser:
No 'Access-Control-Allow-Origin' header is present on the requested resource
This error is all about Cross-Origin Resource Sharing or CORS . Let's see what that's all about.
The same-origin policy and CORS
FSND C2 L3 A04 CORS
The same-origin policy is a concept of web security that allows scripts in Webpage 1 to access data from Webpage 2 only if they share the same domain. This means that the above error will be raised in the following cases:
- Different domains
-
Different subdomains (
example.com
andapi.example.com
) -
Different ports (
example.com
andexample.com:1234
) -
Different protocols (
http://example.com
andhttps://example.com
)
This is not, however, to say that it is really an error. It is behaving exactly as it should. This policy is there to protect you and your users. For instance, attackers may embed malicious scripts in advertisements. This policy prevents those scripts from successfully making requests to your bank's website as you access the website hosting the advertisement.
If you're sending any requests beyond very simple GET or POST requests, then before your actual request is sent, the browser sends a preflight OPTIONS request to the server. If CORS is not enabled, then the browser will not respond properly and the actual request will not be sent.
CORS Quiz
SOLUTION:
- `example.com` and `api.example.com`
- `https://example.com` and `http://example.com`
- `example.com` and `example.com:3000`
CORS headers
FSND C2 L3 A05 CORS Header
In order for the requests to be processed properly, CORS utilizes headers to specify what the server will allow:
-
Access-Control-Allow-Origin
- What client domains can access its resources. For any domain use *
-
Access-Control-Allow-Credentials
- Only if using cookies for authentication - in which case its value must be true
-
Access-Control-Allow-Methods
- List of HTTP request types allowed
-
Access-Control-Allow-Headers
- List of http request header values the server will allow, particularly useful if you use any custom headers